﻿using System;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraBars;
using E4RPDevExpress10;
using E4RPTools;

namespace HouseRental
{
    public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.OwnerWindow = this;
                estimate.Controller = _controller;
                estimateList.Controller = _controller;
                estimateAnalysis.Controller = _controller;
                _controller.EstimateShow += delegate { xtraTabControl.SelectedTabPage = estimateXtraTabPage; };
                _controller.HouseRentalChange += ControllerHouseRentalChange;
                _controller.EstimateStateChange += delegate { SetControlsStatus(); };
            }
        }

        #endregion

        #region Private Methods

        private void SetEstimateControlsStatus()
        {
            newEstimateBarButtonItem.Enabled = false;
            addFamilyProductsBarButtonItem.Enabled = false;
            addProductsBarButtonItem.Enabled = false;
            equalizeBarButtonItem.Enabled = false;
            distributeMonthlyBarButtonItem.Enabled = false;
            applyOnLastYearBarButtonItem.Enabled = false;
            saveEstimateBarButtonItem.Enabled = false;
            printGridBarButtonItem.Enabled = false;
            printPreviewGridBarButtonItem.Enabled = false;
            lockEstimateBarButtonItem.Enabled = false;
            unlockEstimateBarButtonItem.Enabled = false;
            if (_controller == null) return;
            if (string.IsNullOrEmpty(_controller.HouseRentalId)) return;
            newEstimateBarButtonItem.Enabled = true;
            var tabPageSelected = xtraTabControl.SelectedTabPage == estimateXtraTabPage;
            var saved = _controller.Estimate.Orcamento[0].Id > 0;
            var locked = saved && _controller.Estimate.Orcamento[0].Estado == EstimateState.Bloqueado.ToString();
            addFamilyProductsBarButtonItem.Enabled = tabPageSelected && !locked;
            addProductsBarButtonItem.Enabled = tabPageSelected && !locked;
            equalizeBarButtonItem.Enabled = tabPageSelected && !locked;
            distributeMonthlyBarButtonItem.Enabled = tabPageSelected && !locked;
            applyOnLastYearBarButtonItem.Enabled = tabPageSelected && !locked;
            saveEstimateBarButtonItem.Enabled = tabPageSelected && !locked;
            printGridBarButtonItem.Enabled = tabPageSelected && saved;
            printPreviewGridBarButtonItem.Enabled = tabPageSelected && saved;
            var unLocked = _controller != null && _controller.Estimate.Orcamento[0].Id > 0 && _controller.Estimate.Orcamento[0].Estado == EstimateState.Desbloqueado.ToString();
            lockEstimateBarButtonItem.Enabled = tabPageSelected && unLocked;
            unlockEstimateBarButtonItem.Enabled = tabPageSelected && locked;
        }

        private void SetLayoutsControlsStatus()
        {
            loadLayoutBarButtonItem.Enabled = xtraTabControl.SelectedTabPage != estimateXtraTabPage;
            saveLayoutBarButtonItem.Enabled = xtraTabControl.SelectedTabPage != estimateXtraTabPage;
        }

        private void SetAnalysisControlsStatus()
        {            
            analisysReportBarEditItem.Enabled = xtraTabControl.SelectedTabPage == estimateAnalysisXtraTabPage;
            analysisYearBarEditItem.Enabled = xtraTabControl.SelectedTabPage == estimateAnalysisXtraTabPage;
            allHouseRentalsBarEditItem.Enabled = xtraTabControl.SelectedTabPage == estimateAnalysisXtraTabPage;            
            refreshBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == estimateAnalysisXtraTabPage;
            //analysisPrintPreviewBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == estimateAnalysisXtraTabPage;
            //analysisPrintBarButtonItem.Enabled = xtraTabControl.SelectedTabPage == estimateAnalysisXtraTabPage;
        }

        private void SetGridControlsStatus()
        {
            exportToExcelBarButtonItem.Enabled = xtraTabControl.SelectedTabPage != estimateXtraTabPage;
            customizeGridColumnsBarButtonItem.Enabled = xtraTabControl.SelectedTabPage != estimateXtraTabPage;
            printGridBarButtonItem.Enabled = xtraTabControl.SelectedTabPage != estimateXtraTabPage;
            printPreviewGridBarButtonItem.Enabled = xtraTabControl.SelectedTabPage != estimateXtraTabPage;
        }

        private void SetControlsStatus()
        {
            SetEstimateControlsStatus();
            SetLayoutsControlsStatus();
            SetAnalysisControlsStatus();
            SetGridControlsStatus();
        }

        private void SetupDataSetReportData()
        {
            relatorioDataSet.Clear();
            relatorioDataSet.Merge(_controller.GetDataSetReports());
            reportRepositoryItemLookUpEdit.DataSource = relatorioDataSet.Relatorio;
            reportRepositoryItemLookUpEdit.DisplayMember = relatorioDataSet.Relatorio.NomeColumn.ToString();
            reportRepositoryItemLookUpEdit.ValueMember = relatorioDataSet.Relatorio.NomeColumn.ToString();
            reportRepositoryItemLookUpEdit.Columns.Clear();
            reportRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private void SetupDatabaseBeginDateEndDateReportData()
        {
            databaseRelatorioDataSet.Clear();
            databaseRelatorioDataSet.Merge(_controller.GetDatabaseBeginDateEndDateReports());
            databaseReportRepositoryItemLookUpEdit.DataSource = databaseRelatorioDataSet.Relatorio;
            databaseReportRepositoryItemLookUpEdit.DisplayMember = databaseRelatorioDataSet.Relatorio.NomeColumn.ToString();
            databaseReportRepositoryItemLookUpEdit.ValueMember = databaseRelatorioDataSet.Relatorio.NomeColumn.ToString();
            databaseReportRepositoryItemLookUpEdit.Columns.Clear();
            databaseReportRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Nome", "Nome", 70, FormatType.None, "", true, HorzAlignment.Near)});
        }

        private AnalysisFilter GetAnalysisFilter()
        {
            long? year = null;
            if (analysisYearBarEditItem.EditValue.ToString() != "Todos")
                year = Convert.ToInt64(analysisYearBarEditItem.EditValue);
            var allHouseRentals = Convert.ToBoolean(allHouseRentalsBarEditItem.EditValue);
            var purchases = Convert.ToBoolean(purchasesBarEditItem.EditValue);
            var sales = Convert.ToBoolean(salesBarEditItem.EditValue);
            var payments = Convert.ToBoolean(paymentsBarEditItem.EditValue);
            var breakHouseRentals = Convert.ToBoolean(breakHouseRentalBarEditItem.EditValue);
            return new AnalysisFilter(year, allHouseRentals, purchases, sales, payments, breakHouseRentals);
        }

        private ReportFilter GetReportFilter()
        {
            var reportName = analisysReportBarEditItem.EditValue.ToString();
            var report = relatorioDataSet.Relatorio.FindByNome(reportName);
            return new ReportFilter(GetAnalysisFilter(), report.Ficheiro, report.NomeXSD);
        }

        #endregion

        public MainForm()
        {
            InitializeComponent();
            SetControlsStatus();
            analysisPrintBarButtonItem.Enabled = false;
            analysisPrintPreviewBarButtonItem.Enabled = false;
            databaseReportPrintBarButtonItem.Enabled = false;
            databaseReportPreviewBarButtonItem.Enabled = false;
            xtraTabControl.SelectedPageChanged += XtraTabControlSelectedPageChanged;
            ribbon.SelectedPage = mainRibbonPage;
            //
            changeHouseRentalBarButtonItem.ItemClick += ChangeHouseRentalBarButtonItemItemClick;
            // Estimate
            newEstimateBarButtonItem.ItemClick += NewEstimateBarButtonItemItemClick;
            saveEstimateBarButtonItem.ItemClick += SaveEstimateBarButtonItemItemClick;
            equalizeBarButtonItem.ItemClick += EqualizeBarButtonItemItemClick;
            distributeMonthlyBarButtonItem.ItemClick += DistributeMonthlyBarButtonItemItemClick;
            applyOnLastYearBarButtonItem.ItemClick += ApplyOnLastYearBarEditItemItemClick;
            addFamilyProductsBarButtonItem.ItemClick += AddFamilyProductsBarButtonItemItemClick;
            addProductsBarButtonItem.ItemClick += AddProductsBarButtonItemItemClick;
            lockEstimateBarButtonItem.ItemClick += LockEstimateBarButtonItemItemClick;
            unlockEstimateBarButtonItem.ItemClick += UnlockEstimateBarButtonItemItemClick;
            // Analysis
            reportRepositoryItemLookUpEdit.EditValueChanging += ReportRepositoryItemLookUpEditEditValueChanging;
            analysisPrintBarButtonItem.ItemClick += AnalysisPrintBarButtonItemItemClick;
            analysisPrintPreviewBarButtonItem.ItemClick += AnalysisPrintPreviewBarButtonItemItemClick;
            //
            databaseReportRepositoryItemLookUpEdit.EditValueChanging += DatabaseReportRepositoryItemLookUpEditEditValueChanging;
            databaseReportPrintBarButtonItem.ItemClick += DatabaseReportPrintBarButtonItemItemClick;
            databaseReportPreviewBarButtonItem.ItemClick += DatabaseReportPreviewBarButtonItemItemClick;            
            // Layouts
            loadLayoutBarButtonItem.ItemClick += LoadLayoutBarButtonItemItemClick;
            saveLayoutBarButtonItem.ItemClick += SaveLayoutBarButtonItemItemClick;
            // Grid
            exportToExcelBarButtonItem.ItemClick += ExportToExcelBarButtonItemItemClick;
            customizeGridColumnsBarButtonItem.ItemClick += CustomizeGridColumnsBarButtonItemItemClick;
            printPreviewGridBarButtonItem.ItemClick += PrintPreviewGridBarButtonItemItemClick;
            printGridBarButtonItem.ItemClick += PrintGridBarButtonItemItemClick;
            refreshBarButtonItem.ItemClick += RefreshBarButtonItemItemClick;
            //
            aboutBarButtonItem.ItemClick += AboutBarButtonItemItemClick;
            exitBarButtonItem.ItemClick += ExitBarButtonItemItemClick;
            Closing += MainFormClosing;        
        }

        void XtraTabControlSelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            SetControlsStatus();
            layoutNameBarStaticItem.Caption = "";
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _controller.ChangeHouseRental();
            xtraTabControl.SelectedTabPage = estimateXtraTabPage;
            if (string.IsNullOrEmpty(_controller.HouseRentalId))
                return;
            _controller.NewEstimate();
            SetControlsStatus();
        }

        void ControllerHouseRentalChange(object sender, EventArgs e)
        {
            houseRentalNameBarStaticItem.Caption = _controller.HouseRentalName;

            SetupDataSetReportData();                            

            var years = _controller.GetYears();
            analysisYearRepositoryItemComboBox.Items.AddRange(years);
            long? year = null;
            if (years.Contains(DateTime.Now.Year.ToString()))
                year = DateTime.Now.Year;
            analysisYearBarEditItem.EditValue = year == null ? "Todos" : year.ToString();
            allHouseRentalsBarEditItem.EditValue = false;
            purchasesBarEditItem.EditValue = true;
            salesBarEditItem.EditValue = true;
            paymentsBarEditItem.EditValue = true;
            estimateAnalysis.RefreshData(GetAnalysisFilter());

            SetupDatabaseBeginDateEndDateReportData();
        }


        void ChangeHouseRentalBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            if (!_controller.ExistsOpenedEstimate(this, "Deseja mesmo alterar o condomínio?"))
                return;
            _controller.ChangeHouseRental();
            xtraTabControl.SelectedTabPage = estimateXtraTabPage;
            if (!string.IsNullOrEmpty(_controller.HouseRentalId))
                _controller.NewEstimate();
        }

        void NewEstimateBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            if (!_controller.ExistsOpenedEstimate(this, "Deseja mesmo efectuar um novo orçamento?"))
                return;
            xtraTabControl.SelectedTabPage = estimateXtraTabPage;
            _controller.NewEstimate();
            SetControlsStatus();
        }

        void SaveEstimateBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            estimate.CloseEditors();
            estimate.ClearControlErrors();
            Result result = _controller.IsEstimateValid();
            if (result.Failed || _controller.Estimate.HasErrors)
            {
                estimate.SetControlErrors(result);
                if (_controller.Estimate.Orcamento[0].RowError != "")
                    MessageBox.Show(this, _controller.Estimate.Orcamento[0].RowError, "Orçamento", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _controller.SaveEstimate(this);
        }

        void DistributeMonthlyBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            estimate.CloseEditors();
            _controller.Distribute(estimate.SelectedEstimateItems(), estimate.GetValue());
            estimate.SetFocusedColumnAsTotal();
        }

        void EqualizeBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            estimate.CloseEditors();
            _controller.Equalize(estimate.SelectedEstimateItems(), estimate.GetValue());
            estimate.SetFocusedColumnAsTotal();
        }

        void ApplyOnLastYearBarEditItemItemClick(object sender, ItemClickEventArgs e)
        {
            estimate.CloseEditors();
            _controller.ApplyOnLastYear(estimate.SelectedEstimateItems());
            estimate.SetFocusedColumnAsTotal();
        }

        void AddFamilyProductsBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.AddFamilyProducts();
        }

        void UnlockEstimateBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.UnLockEstimate();
        }

        void LockEstimateBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            if (!_controller.ExistsOpenedEstimate(this, "Deseja mesmo bloquear o orçamento?"))
                return;
            _controller.LockEstimate();
        }

        void AddProductsBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.AddProducts();
        }

        
        void ReportRepositoryItemLookUpEditEditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            analysisPrintBarButtonItem.Enabled = e.NewValue != null && xtraTabControl.SelectedTabPage == estimateAnalysisXtraTabPage;
            analysisPrintPreviewBarButtonItem.Enabled = e.NewValue != null && xtraTabControl.SelectedTabPage == estimateAnalysisXtraTabPage;
        }

        void AnalysisPrintPreviewBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.PrintPreview(GetReportFilter());
        }

        void AnalysisPrintBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.Print(GetReportFilter());
        }

        void RefreshBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            estimateAnalysis.RefreshData(GetAnalysisFilter());
        }
        
        void SaveLayoutBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            var gridView = ((IGridView)control).GridView();
            var listName = ((IGridView)control).ListName;
            var layoutName = _controller.SaveLayout(this, listName, DevExpressHelper.SaveLayoutToXml(gridView));
            if (layoutName != "")
                layoutNameBarStaticItem.Caption = layoutName;
        }

        void LoadLayoutBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            var gridView = ((IGridView)control).GridView();
            var listName = ((IGridView)control).ListName;
            var layoutName = _controller.LoadLayout(gridView, listName);
            if (layoutName != "")
                layoutNameBarStaticItem.Caption = layoutName;
        }


        void DatabaseReportPreviewBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var reportName = databaseReporBarEditItem.EditValue.ToString();
            var report = databaseRelatorioDataSet.Relatorio.FindByNome(reportName);
            if (reportBeginDatebarEditItem.EditValue == null || reportEndDateBarEditItem.EditValue == null)
                return;
            _controller.PrintPreviewDatabase(report.Ficheiro, Convert.ToDateTime(reportBeginDatebarEditItem.EditValue), Convert.ToDateTime(reportEndDateBarEditItem.EditValue));
        }

        void DatabaseReportPrintBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var reportName = databaseReporBarEditItem.EditValue.ToString();
            var report = databaseRelatorioDataSet.Relatorio.FindByNome(reportName);
            if (reportBeginDatebarEditItem.EditValue == null || reportEndDateBarEditItem.EditValue == null)
                return;
            _controller.PrintDatabase(report.Ficheiro, Convert.ToDateTime(reportBeginDatebarEditItem.EditValue), Convert.ToDateTime(reportEndDateBarEditItem.EditValue));
        }

        void DatabaseReportRepositoryItemLookUpEditEditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            databaseReportPreviewBarButtonItem.Enabled = e.NewValue != null;
            databaseReportPrintBarButtonItem.Enabled = e.NewValue != null;
        }


        void ExportToExcelBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            DevExpressHelper.ExportToExcel(((IGridView)control).GridView());
        }

        void CustomizeGridColumnsBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            DevExpressHelper.ColumnsCustomization(((IGridView)control).GridView());
        }        

        void PrintGridBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            var gridView = ((IGridView)control).GridView();
            gridView.GridControl.Print();
            DevExpressHelper.Print(gridView);
        }

        void PrintPreviewGridBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var control = xtraTabControl.SelectedTabPage.Controls[0];
            var gridView = ((IGridView)control).GridView();
            DevExpressHelper.ShowPrintPreview(gridView);
        }
        

        static void AboutBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            var product = new AboutLabelControl("House Rental", new Font("Jokerman", 24F, FontStyle.Regular, GraphicsUnit.Point, 0),
                                                Color.ForestGreen, new Point(127, 38));
            var form = new AboutXtraForm { Version = "1.0.0.0", Product = product};
            form.ShowDialog();
        }

        void ExitBarButtonItemItemClick(object sender, ItemClickEventArgs e)
        {
            _controller.CloseConnection();
            Close();
        }

        void MainFormClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _controller.CloseConnection();
        }

    }
}